package com.xinhe.web.selfpay;

import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.exception.HttpException;
import com.wechat.pay.java.core.exception.MalformedMessageException;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.*;
import com.xinhe.web.enums.EAssetType;
import com.xinhe.web.reposity.AdoptedTreeOrderRepository;
import com.xinhe.web.reposity.MemberRepository;
import com.xinhe.web.reposity.ValueConfigRepository;
import com.xinhe.web.reposity.WeixinTradeCpRepository;
import com.xinhe.web.service.AssetCountService;
import com.xinhe.web.util.HttpServletRequestUtil;
import com.xinhe.web.util.Snowflake;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;

@Slf4j
@Service
public class WeixinJsapiService {
    @Autowired
    WeixinTradeCpRepository weixinTradeCpRepository;
    @Autowired
    AdoptedTreeOrderRepository adoptedTreeOrderRepository;
    @Autowired
    AssetCountService assetCountService;
    @Autowired
    MemberRepository memberRepository;
    @Autowired
    ValueConfigRepository valueConfigRepository;


    /*private final ResourceLoader resourceLoader;

    public WeixinJsapiService(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }*/

    @Autowired
    private static ResourceLoader resourceLoader;
    @Autowired
    NotificationConfig config;

    /*我的信息
        userid：604183377410523136
        openid：olYZb5aMoVTziZtD8MYK5dIV8TmE
        unionid：oaniQ6U5MUVuwINMyxdA-K4f8yWg
        configid：519802482830868480
        appid：wx2425d0af98810b00
        appsecret：f74746117f13a69ef272055921e81b3f
        mchid:1616713201
        paykey:af42f8b7ecc71d8995b8f98bd6baad28
        证书序列号：57906AE4C493222D0DDD03D81A3A2F2AA93B8D19
        apiV3Key：12345678901234567890ABCDEFGHIJKL
        */

    /** 商户号 */
    public static String merchantId = "1616713201";
    /** 商户API私钥路径 */
    public static String privateKeyPath = "";
    /** 商户证书序列号 */
    public static String merchantSerialNumber = "57906AE4C493222D0DDD03D81A3A2F2AA93B8D19";
    /** 商户APIV3密钥 */
    public static String apiV3Key = "12345678901234567890ABCDEFGHIJKL";

    /*public static NotificationConfig config = null;
    static {
        Resource resource = resourceLoader.getResource("classpath:cert/apiclient_key.pem");
        //String privateKeyPath = resource.getFile().getAbsolutePath();
        String privateKeyPath = null;
        try {
            privateKeyPath = resource.getFile().getPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 使用自动更新平台证书的RSA配置
        // 一个商户号只能初始化一个配置，否则会因为重复的下载任务报错
        config = new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId)
                        .privateKeyFromPath(privateKeyPath)
                        .merchantSerialNumber(merchantSerialNumber)
                        .apiV3Key(apiV3Key)
                        .build();
    }*/

    public Result jsapiPay(PrepayRequest prepayRequest){
        String privateKeyPath = null;
        //todo 注意本地运行的话可以使用这种绝对路径的方式，线上的话使用相对路径，记得改成docker容器内部的证书路径
        //本地运行，打开
        /*Resource resource = resourceLoader.getResource("classpath:cert/apiclient_key.pem");
        try {
            privateKeyPath = resource.getFile().getPath();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        //线上运行，打开
        privateKeyPath="/zhanghou/apiclient_key.pem";
        // 使用自动更新平台证书的RSA配置
        // 一个商户号只能初始化一个配置，否则会因为重复的下载任务报错
        Config config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId)
                        .privateKeyFromPath(privateKeyPath)
                        .merchantSerialNumber(merchantSerialNumber)
                        .apiV3Key(apiV3Key)
                        .build();
        JsapiService service = new JsapiService.Builder().config(config).build();
        // request.setXxx(val)设置所需参数，具体参数可见Request定义
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(1);
        request.setAmount(amount);
        request.setAppid("wx2425d0af98810b00");
        request.setMchid("1616713201");
        request.setDescription("测试商品标题");
        request.setNotifyUrl("http://1941w5190a.yicp.fun:49760/test/acceptWeixin");
        request.setOutTradeNo("out_trade_no_888");
        Payer payer = new Payer();
        payer.setOpenid("olYZb5aMoVTziZtD8MYK5dIV8TmE88");
        request.setPayer(payer);
        try {
            PrepayResponse response = service.prepay(request);
            System.out.println("哈哈哈："+ JSONObject.toJSONString(response));
            return Result.ok(response.getPrepayId());
        } catch (HttpException e) { // 发送HTTP请求失败
            e.printStackTrace();
            return Result.failed(111,e.getMessage());
        } catch (ServiceException e) { // 服务返回状态小于200或大于等于300，例如500
            // 调用e.getResponseBody()获取返回体打印日志或上报监控，更多方法见ServiceException定义
            return Result.failed(e.getHttpStatusCode(),e.getErrorMessage());
        } catch (MalformedMessageException e) { // 服务返回成功，返回体类型不合法，或者解析返回体失败
            // 调用e.getMessage()获取信息打印日志或上报监控，更多方法见MalformedMessageException定义
            return Result.failed(112,e.getMessage());
        }

    }

    @Transactional(rollbackFor = {Exception.class})
    public ResponseEntity.BodyBuilder payCallback(HttpServletRequest request, HttpServletResponse response) {
        String resp = HttpServletRequestUtil.readAsChars(request);
        String signature = request.getHeader("Wechatpay-Signature");
        String serial = request.getHeader("Wechatpay-Serial");
        String nonce = request.getHeader("Wechatpay-Nonce");
        String timestamp = request.getHeader("Wechatpay-Timestamp");
        String signatureType = request.getHeader("Wechatpay-Signature-Type");
        // 构造 RequestParam
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(serial)
                .nonce(nonce)
                .signature(signature)
                .timestamp(timestamp)
                .body(resp)
                .build();
        // 初始化 NotificationParser
        NotificationParser parser = new NotificationParser(config);
        try {
            // 以支付通知回调为例，验签、解密并转换成 Transaction
            Transaction transaction = parser.parse(requestParam, Transaction.class);
            //保存微信支付记录。注意只要回调了一定代表是成功的，只有成功支付了微信才会回调。所以WeixinTradeCp表只有回调了才有数据，即：成功
            WeixinTradeCp weixinTradeCpIsExists = this.weixinTradeCpRepository.findByOutTradeNo(transaction.getOutTradeNo());
           //已经回调成功，不用再次处理
            if (!Objects.isNull(weixinTradeCpIsExists)) {
                return ResponseEntity.status(HttpStatus.OK);
            }
            WeixinTradeCp weixinTradeCp = new WeixinTradeCp();
            weixinTradeCp.setAmount(transaction.getAmount().getPayerTotal());
            weixinTradeCp.setId(Snowflake.generateId());
            //状态：交易中
            weixinTradeCp.setTradeState(transaction.getTradeState().name());
            weixinTradeCp.setTradeType(transaction.getTradeType().name());
            weixinTradeCp.setOutTradeNo(transaction.getOutTradeNo());
            weixinTradeCp.setTransactionId(transaction.getTransactionId());
            weixinTradeCp.setCreateTime(new Date());
            weixinTradeCp.setRemoved(0);
            weixinTradeCp.setRsp(JSONObject.toJSONString(transaction));
            this.weixinTradeCpRepository.save(weixinTradeCp);
            //假如订单表显示UN_PAY，更新订单表的支付状态位PAY
            AdoptedTreeOrder order = this.adoptedTreeOrderRepository.findById(Long.valueOf(weixinTradeCp.getOutTradeNo())).get();
            if (order != null && order.getStatus().equals("UN_PAY")) {
                order.setPayChannel("WEIXIN_JSAPI");
                order.setPayTime(new Date());
                paySuccess(order);
            }
        } catch (Exception e) {
            // 签名验证失败，返回 401 UNAUTHORIZED 状态码
            log.error("sign verification failed", e);
            log.info(HttpStatus.UNAUTHORIZED.value()+HttpStatus.UNAUTHORIZED.getReasonPhrase());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED);
        }
        // 处理成功，返回 200 OK 状态码
        return ResponseEntity.status(HttpStatus.OK);

        /*Result result = this.getWeixinPayNotifyDataAndValidateAndUpdateWeixinTrade();
        if (0 != result.getCode()) {
            return result;
        }
        WeixinPayNotifyView view = (WeixinPayNotifyView)result.getData();
        WeixinTrade weixinTrade = view.getWeixinTrade();
        AdoptedTreeOrder order = this.adoptedTreeOrderRepository.findById(weixinTrade.getDataId()).get();
        if (order != null && order.getStatus().equals("UN_PAY")) {
            order.setPayChannel("WEIXIN_JSAPI");
            order.setPayTime(new Date());
            paySuccess(order);
        }
        return result;*/
    }
    private void paySuccess(AdoptedTreeOrder order) {
        order.setStatus("PAY");
        Calendar calendar = Calendar.getInstance();
        //认养时间
        order.setStartTime(calendar.getTime());
        calendar.add(1, order.getAdoptedYear().intValue());
        //到期时间,1年后到期
        order.setEndTime(calendar.getTime());
        this.adoptedTreeOrderRepository.saveAndFlush(order);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //订单总赠送的云茶籽
        if (order.getOrderYunChaSeed().compareTo(BigDecimal.ZERO) > 0) {
            Date parse = null;
            try {
                Result<AssetDetail> beanResult;
                parse = format.parse("2024-01-01");
                if (parse.compareTo(new Date()) > 0) {
                    beanResult = this.assetCountService.saveRemainderAsset(order.getfUserId(),"YUN_CHA_SEED","ADOPTED_TREE",order
                            .getOrderYunChaSeed(), order.getId(),"",new Date());
                } else {
                    beanResult = this.assetCountService.saveRemainderAsset(order.getfUserId(), "NEW_YUN_CHA_SEED","ADOPTED_TREE", order
                            .getOrderYunChaSeed(), order.getId(),"",new Date());
                }
                if (0 != beanResult.getCode()) {
                    log.error("认养云茶籽失败【{}】,订单：{}", EAssetType.YUN_CHA_SEED.getName(), order.getId());
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        //订单总赠送的茶油卡
        if (order.getOrderTeaOilCard().compareTo(BigDecimal.ZERO) > 0) {
            Result<AssetDetail> beanResult = this.assetCountService.saveRemainderAsset(order.getfUserId(),"TEA_OIL_CARD","ADOPTED_OIL_CARD", order
                    .getOrderTeaOilCard(), order.getId(),"",new Date());
            if (0 != beanResult.getCode()) {
                log.error("认养云茶籽失败【{}】,订单：{}", EAssetType.TEA_OIL_CARD.getName(), order.getId());
            }
        }
        //订单总赠送的消费金红包
        if (order.getOrderConsumerGoldRedEnvelope().compareTo(BigDecimal.ZERO) > 0) {
            Result<AssetDetail> beanResult = this.assetCountService.saveRemainderAsset(order.getfUserId(),"CONSUMER_GOLD_RED_ENVELOPE","ADOPTED_CONSUMER_GOLD_RED_ENVELOPE", order
                    .getOrderConsumerGoldRedEnvelope(), order.getId(),"",new Date());
            if (0 != beanResult.getCode()) {
                log.error("认养云茶籽失败【{}】,订单：{}", EAssetType.CONSUMER_GOLD_RED_ENVELOPE.getName(), order.getId());
            }
        }
        //1、成功认养后，芯禾会员升级为家园天使 2、更新认养总的数量
        Member member = this.memberRepository.findByUserId(order.getfUserId());
        if ("COMMON".equals(member.getLevel())) {
            member.setLevel("HOME_ANGEL");
        }
        member.setAdoptionDate(new Date());
        member.setAdoptionNum(Integer.valueOf(member.getAdoptionNum().intValue() + order.getAmount().intValue()));
        this.memberRepository.saveAndFlush(member);
        //是否导入用户 0是 1否
        if (1 == member.getIsImportMember().intValue()) {
            //查询配置的创始人首次购买数量，20
            Optional<ValueConfig> optional = valueConfigRepository.findById("founder_first_purchase_quantity");
            Integer founder_first_purchase_quantity = Integer.valueOf(optional.get().getValue());
            if ("FOUNDER".equals(member.getRole()) && member.getAdoptionNum().intValue() >= founder_first_purchase_quantity &&
                    StringUtils.isNotBlank(member.getParentCode())) {
                Member parentMember = this.memberRepository.findByCode(member.getParentCode());
                if (null != parentMember) {
                    //更新推荐人脱离关系前的认养数量
                    parentMember.setDisengageNo(order.getAmount());//todo
                    this.memberRepository.saveAndFlush(parentMember);
                    Result result = this.assetCountService.findByTypeAndUserId("YUN_CHA_SEED", parentMember.getFUserId());
                    AssetCount assetCount = (AssetCount) result.getData();
                    //更新一下推荐人资产。查询一下配置的“推荐创始人奖励” 2250
                    Optional<ValueConfig> valueConfigOptional = valueConfigRepository.findById("recommended_founder_rewards");
                    BigDecimal recommended_founder_rewards = new BigDecimal(valueConfigOptional.get().getValue());
                    this.assetCountService.saveRemainderAsset(parentMember.getFUserId(),"RMB","FOUNDER_REWARDS",recommended_founder_rewards, parentMember.getId(),
                            String.format("推荐创始人%s%s认养%s棵获得奖励", new Object[] { member.getName(), member.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"), order.getAmount() }),new Date());
                    Result result1 = this.assetCountService.findByTypeAndUserId("YUN_CHA_SEED", parentMember.getFUserId());
                    AssetCount assetCount1 = (AssetCount) result1.getData();
                    //查询配置的推荐创始人解冻云茶籽，2250
                    Optional<ValueConfig> valueConfigOptiona2 = valueConfigRepository.findById("recommend_founder_thawing");
                    BigDecimal recommend_founder_thawing = new BigDecimal(valueConfigOptiona2.get().getValue());
                    //如果推荐人剩余的>配置的2250
                    if (assetCount1.getRemainder().compareTo(recommend_founder_thawing) >= 0) {
                        //更新一下推荐人资产。推荐创始人解冻云茶籽
                        Result beanResult1 = this.assetCountService.saveRemainderAsset(parentMember.getFUserId(),"YUN_CHA_SEED","RECOMMEND_FOUNDER_THAWING",
                                recommend_founder_thawing.negate(), order.getId(),"",new Date());
                        if (0 == beanResult1.getCode()) {
                            this.assetCountService.saveRemainderAsset(parentMember.getFUserId(),"RMB","RECOMMEND_FOUNDER_THAWING",
                                    recommend_founder_thawing, order.getId(),"",new Date());
                        }
                    }else{
                        //如果推荐人剩余的不够解冻配置的2250,那就剩多少解冻多少
                        BigDecimal difference = recommend_founder_thawing.subtract(assetCount.getRemainder());
                        if (assetCount.getRemainder().compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal remainder = assetCount.getRemainder();
                            Result beanResult1 = this.assetCountService.saveRemainderAsset(parentMember.getFUserId(),"YUN_CHA_SEED","RECOMMEND_FOUNDER_THAWING", remainder
                                    .negate(), order.getId(),"",new Date());
                            if (0 == beanResult1.getCode()) {
                                this.assetCountService.saveRemainderAsset(parentMember.getFUserId(),"RMB","RECOMMEND_FOUNDER_THAWING", remainder, order
                                        .getId(),"",new Date());
                            }
                        }
                        //查询新资产类型的（20240101之后认养的）剩余量
                        Result result2 = this.assetCountService.findByTypeAndUserId("NEW_YUN_CHA_SEED", parentMember.getFUserId());
                        AssetCount assetCount2 = (AssetCount) result2.getData();
                        if (null != assetCount2 && assetCount2.getRemainder().compareTo(BigDecimal.ZERO) > 0) {
                            //够的话继续解冻
                            if (assetCount2.getRemainder().compareTo(difference) > 0) {
                                Result beanResult2 = this.assetCountService.saveRemainderAsset(parentMember.getFUserId(),"NEW_YUN_CHA_SEED","RECOMMEND_FOUNDER_THAWING", difference
                                        .negate(), order.getId(),"",new Date());
                                if (0 == beanResult2.getCode()) {
                                    this.assetCountService.saveRemainderAsset(parentMember.getFUserId(),"RMB","RECOMMEND_FOUNDER_THAWING", difference, order
                                            .getId(),"",new Date());
                                }
                            } else {
                                //够的话解冻新资产类型剩余的
                                BigDecimal remainder = assetCount2.getRemainder();
                                Result beanResult2 = this.assetCountService.saveRemainderAsset(parentMember.getFUserId(),"NEW_YUN_CHA_SEED","RECOMMEND_FOUNDER_THAWING", remainder
                                        .negate(), order.getId(),"",new Date());
                                if (0 == beanResult2.getCode()) {
                                    this.assetCountService.saveRemainderAsset(parentMember.getFUserId(),"RMB","RECOMMEND_FOUNDER_THAWING", remainder, order
                                            .getId(),"",new Date());
                                }
                            }
                        }
                    }
                    //解除推荐关系
                    member.setParentCode(null);
                    this.memberRepository.saveAndFlush(member);
                }
            }
        }
        //有推荐人
        if (StringUtils.isNotBlank(member.getParentCode())) {
            Member parent = this.memberRepository.findByCode(member.getParentCode());
            if (parent != null) {
                //查询配置的直推解冻云茶籽数量，75
                Optional<ValueConfig> optional = valueConfigRepository.findById("two_thaw_yun_cha_seed_amount");
                BigDecimal twoYunChaSeed = new BigDecimal(optional.get().getValue());
                BigDecimal twoYunChaSeedMoney = twoYunChaSeed.multiply(new BigDecimal(order.getAmount().intValue()));
                Result result = this.assetCountService.findByTypeAndUserId("YUN_CHA_SEED", parent.getFUserId());
                AssetCount assetCount = (AssetCount) result.getData();
                //剩余量够的话直接解冻
                if (assetCount.getRemainder().compareTo(twoYunChaSeedMoney) >= 0) {
                    Result beanResult = this.assetCountService.saveRemainderAsset(parent.getFUserId(),"YUN_CHA_SEED","TWO_THAW_YUN_CHA_SEED", twoYunChaSeedMoney
                            .negate(), order.getId(),"",new Date());
                    if (0 == beanResult.getCode()) {
                        this.assetCountService.saveRemainderAsset(parent.getFUserId(),"RMB","TWO_THAW_YUN_CHA_SEED", twoYunChaSeedMoney, order
                                .getId(),"",new Date());
                    }
                } else {
                    //剩余量不够的话有多少解冻多少
                    BigDecimal difference = twoYunChaSeedMoney.subtract(assetCount.getRemainder());
                    if (assetCount.getRemainder().compareTo(BigDecimal.ZERO) > 0) {
                        BigDecimal remainder = assetCount.getRemainder();
                        Result beanResult = this.assetCountService.saveRemainderAsset(parent.getFUserId(),"YUN_CHA_SEED","TWO_THAW_YUN_CHA_SEED", remainder
                                .negate(), order.getId(),"",new Date());
                        if (0 == beanResult.getCode()) {
                            this.assetCountService.saveRemainderAsset(parent.getFUserId(),"RMB","TWO_THAW_YUN_CHA_SEED", remainder, order
                                    .getId(),"",new Date());
                        }
                    }
                    //查询新资产类型的（20240101之后认养的）剩余量,接着解冻
                    Result result3 = this.assetCountService.findByTypeAndUserId("NEW_YUN_CHA_SEED", parent.getFUserId());
                    AssetCount assetCount3 = (AssetCount) result3.getData();
                    if (null != assetCount3 &&
                            assetCount3.getRemainder().compareTo(BigDecimal.ZERO) > 0) {
                        if (assetCount3.getRemainder().compareTo(difference) > 0) {
                            Result beanResult2 = this.assetCountService.saveRemainderAsset(parent.getFUserId(),"NEW_YUN_CHA_SEED","TWO_THAW_YUN_CHA_SEED", difference
                                    .negate(), order.getId(),"",new Date());
                            if (0 == beanResult2.getCode()) {
                                this.assetCountService.saveRemainderAsset(parent.getFUserId(),"RMB","TWO_THAW_YUN_CHA_SEED", difference, order
                                        .getId(),"",new Date());
                            }
                        } else {
                            BigDecimal remainder = assetCount3.getRemainder();
                            Result beanResult2 = this.assetCountService.saveRemainderAsset(parent.getFUserId(),"NEW_YUN_CHA_SEED","TWO_THAW_YUN_CHA_SEED", remainder
                                    .negate(), order.getId(),"",new Date());
                            if (0 == beanResult2.getCode()) {
                                this.assetCountService.saveRemainderAsset(parent.getFUserId(),"RMB","TWO_THAW_YUN_CHA_SEED", remainder, order
                                        .getId(),"",new Date());
                            }
                        }
                    }
                }
                //配置的直推奖励余额,225
                Optional<ValueConfig> optiona2 = valueConfigRepository.findById("two_thaw_reward");
                BigDecimal twoFee = new BigDecimal(optiona2.get().getValue());
                BigDecimal twoFeeMoney = twoFee.multiply(new BigDecimal(order.getAmount().intValue()));
                this.assetCountService.saveRemainderAsset(parent.getFUserId(),"RMB","TWO_THAW_REWARD", twoFeeMoney, order
                        .getId(), String.format("直推%s%s认养%s棵获得奖励", new Object[] { member.getName(), member.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"), order.getAmount() }),new Date());
                //推荐人有上级推荐人
                if (StringUtils.isNotBlank(parent.getParentCode())) {
                    Member threeMember = this.memberRepository.findByCode(parent.getParentCode());
                    if (threeMember != null) {
                        //配置的间推解冻云茶籽数量,45
                        Optional<ValueConfig> optiona3 = valueConfigRepository.findById("three_thaw_yun_cha_seed_amount");
                        BigDecimal threeYunChaSeed = new BigDecimal(optiona3.get().getValue());
                        BigDecimal threeYunChaSeedMoney = threeYunChaSeed.multiply(new BigDecimal(order.getAmount().intValue()));
                        Result result1 = this.assetCountService.findByTypeAndUserId("YUN_CHA_SEED", threeMember.getFUserId());
                        assetCount = (AssetCount) result1.getData();
                        if (assetCount.getRemainder().compareTo(threeYunChaSeedMoney) >= 0) {
                            Result beanResult = this.assetCountService.saveRemainderAsset(threeMember.getFUserId(),"YUN_CHA_SEED","THREE_THAW_YUN_CHA_SEED", threeYunChaSeedMoney
                                    .negate(), order.getId(),"",new Date());
                            if (0 == beanResult.getCode()) {
                                this.assetCountService.saveRemainderAsset(threeMember.getFUserId(),"RMB","THREE_THAW_YUN_CHA_SEED", threeYunChaSeedMoney, order
                                        .getId(),"",new Date());
                            }
                        } else {
                            BigDecimal difference = twoYunChaSeedMoney.subtract(assetCount.getRemainder());
                            if (assetCount.getRemainder().compareTo(BigDecimal.ZERO) > 0) {
                                BigDecimal remainder = assetCount.getRemainder();
                                Result beanResult = this.assetCountService.saveRemainderAsset(threeMember.getFUserId(),"YUN_CHA_SEED","THREE_THAW_YUN_CHA_SEED", remainder
                                        .negate(), order.getId(),"",new Date());
                                if (0 == beanResult.getCode()) {
                                    this.assetCountService.saveRemainderAsset(threeMember.getFUserId(), "RMB","THREE_THAW_YUN_CHA_SEED", remainder, order
                                            .getId(),"",new Date());
                                }
                            }
                            Result result3 = this.assetCountService.findByTypeAndUserId("NEW_YUN_CHA_SEED", threeMember.getFUserId());
                            AssetCount assetCount3 = (AssetCount)result3.getData();
                            if (null != assetCount3 &&
                                    assetCount3.getRemainder().compareTo(BigDecimal.ZERO) > 0) {
                                if (assetCount3.getRemainder().compareTo(difference) > 0) {
                                    Result beanResult2 = this.assetCountService.saveRemainderAsset(threeMember.getFUserId(),"NEW_YUN_CHA_SEED", "THREE_THAW_YUN_CHA_SEED", difference
                                            .negate(), order.getId(),"",new Date());
                                    if (0 == beanResult2.getCode()) {
                                        this.assetCountService.saveRemainderAsset(threeMember.getFUserId(),"RMB","THREE_THAW_YUN_CHA_SEED", difference, order
                                                .getId(),"",new Date());
                                    }
                                } else {
                                    BigDecimal remainder = assetCount3.getRemainder();
                                    Result beanResult2 = this.assetCountService.saveRemainderAsset(threeMember.getFUserId(),"NEW_YUN_CHA_SEED", "THREE_THAW_YUN_CHA_SEED", remainder
                                            .negate(), order.getId(),"",new Date());
                                    if (0 == beanResult2.getCode()) {
                                        this.assetCountService.saveRemainderAsset(threeMember.getFUserId(),"RMB","THREE_THAW_YUN_CHA_SEED", remainder, order
                                                .getId(),"",new Date());
                                    }
                                }
                            }
                        }
                        //配置的间推奖励余额,105
                        Optional<ValueConfig> optiona4 = valueConfigRepository.findById("three_thaw_reward");
                        BigDecimal threeFee = new BigDecimal(optiona4.get().getValue());
                        BigDecimal threeFeeMoney = threeFee.multiply(new BigDecimal(order.getAmount().intValue()));
                        this.assetCountService.saveRemainderAsset(threeMember.getFUserId(),"RMB","THREE_THAW_REWARD", threeFeeMoney, order
                                .getId(), String.format("间推%s%s认养%s棵获得奖励", new Object[] { member.getName(), member.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"), order.getAmount() }),new Date());
                    }
                }
                if (null != parent.getFServiceId()) {
                    member.setFServiceId(parent.getFServiceId());
                }
            }
        }
    }


}
